import Vue from 'vue';
import Loading from './index.vue';
const LoadingConstructor = Vue.extend(Loading);


const loadingDirective = {};
loadingDirective.install = Vue => {
    if (Vue.prototype.$isServer) return;
    const toggleLoading = (el, binding) => {
        if (binding.value) {
            // 是否全屏
            el.style.position = binding.modifiers.fullscreen ? 'fixed' : 'relative';
            el.instance.visible = true;
            el.appendChild(el.mask)
        } else {
            el.instance.visible = false;
        }
    }

    Vue.directive('loading', {
        bind: function (el, binding, vnode) {
            const textExr = el.getAttribute('uap-loading-text');
            const backgroundExr = el.getAttribute('uap-loading-background');
            const customClassExr = el.getAttribute('uap-loading-custom-class');
            const vm = vnode.context;
            const mask = new LoadingConstructor({
                el: document.createElement('div'),
                data: {
                    text: vm && vm[textExr] || textExr,
                    background: vm && vm[backgroundExr] || backgroundExr,
                    customClass: vm && vm[customClassExr] || customClassExr,
                    fullscreen: !!binding.modifiers.fullscreen
                }
            });
            el.instance = mask;
            el.mask = mask.$el;
            binding.value && toggleLoading(el, binding);
        },
        update: function (el, binding) {
            // 更新时更新text
            el.instance.setText(el.getAttribute('uap-loading-text'));
            if (binding.oldValue !== binding.value) {
                toggleLoading(el, binding);
            }
        },
        unbind: function (el, binding) {
            console.log(el)
            console.log(binding)
        }
    })
}



export default loadingDirective;
